package com.bit.blog.common.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.Map;

@Slf4j
public class JwtUtils {
    private static final String secretString = "Ks6iI3xweuHqTOQQX4UA3UnUL7xoLI2TCwLzv5dsK4c=";
    private static final SecretKey key = Keys.hmacShaKeyFor(Decoders.BASE64URL.decode(secretString));
    private static final long EXPIRE_TIME = 7 * 24* 60 * 60 * 1000; //过期时间: 7天

    /**
     * 生成token
     * @param claims
     * @return
     */
    public static String genToken(Map<String, Object> claims){
        return Jwts.builder().setClaims(claims)  //设置payload
                .setIssuedAt(new Date())   //设置签发时间
                .setExpiration(new Date(System.currentTimeMillis()+EXPIRE_TIME))   //设置过期时间  30分钟过期
                .signWith(key)   //设置签名
                .compact();   //生成token
    }

    /**
     * 解析token
     * @param token
     * @return
     */
    public static Claims parseToken(String token){
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
        Claims body = null;
        try {
             body = build.parseClaimsJws(token).getBody();
        }catch (Exception e){
            log.error("token解析失败, token:"+ token);
        }
        return body;

    }
}
